/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bitetorrent;

import bitetorrent.helper.Digest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Robert Gunawan
 */
public class Torrent {

    //attribut class (public semua saja dulu --")
    public String fileName;
    public byte[] infoHash;
    public int fileLength;
    public int pieceSize;
    public String announce;
    public String[] pieces;

    //method class
    public void CreateTorrent(String namaFile, String NamaFileTujuan, int ukuranFile, String URL) throws NoSuchAlgorithmException, UnsupportedEncodingException //create torrent file dari NamaFile ke NamaFileTujuan
    {
        byte[] bytes = BacaFile(namaFile);
        File tempfile = new File(namaFile);
        
        StringBuilder sb = new StringBuilder();
        for (int j =0 ; j < bytes.length; ++j) {
            sb.append((char)bytes[j]);
        }

        String piece = sb.toString();
        pieceSize = ukuranFile; //asumsi min 128 KB yang dipieces-kan
        fileName = tempfile.getName(); //lebih aman pake file name aja, bukan path komplit
        infoHash = Digest.SHA1InByte(fileName);
        fileLength = bytes.length;
        announce = URL; //ini masih belum ngerti gimana ntar pakainya, kalo URL, apakah sama dengan nama file?

        //di sini mulai save filenya
        String Baris1 = fileName + " " + fileLength + " " + pieceSize;
        String Baris2 = announce;

        int jumlahbagian = fileLength / pieceSize;
        if (fileLength % pieceSize != 0) {
            jumlahbagian++;
        }

        System.out.println("file length : " + fileLength);
        pieces = new String[jumlahbagian];
        int i;
        for (i = 0; i < jumlahbagian - 1; i++) {
            pieces[i] = Digest.SHA1(piece.substring(i * ukuranFile, (i + 1) * ukuranFile));
        }
        pieces[i] = Digest.SHA1(piece.substring(i * ukuranFile));
        ArrayList<String> TempString = new ArrayList<String>();
        TempString.add(Baris1);
        TempString.add(Baris2);
        for (i = 0; i < pieces.length; i++) {
            TempString.add(pieces[i]);
        }
        //.add(Baris3);

        //bagian save file
        File f = new File(NamaFileTujuan);
        try {
            FileWriter in = new FileWriter(f);
            PrintWriter out = new PrintWriter(in);
            in.flush();
            for (i = 0; i < TempString.size(); i++) {
                out.println(TempString.get(i));
            }
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(Torrent.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void ReadTorrent(String NamaFileTorrent) throws UnsupportedEncodingException, NoSuchAlgorithmException //ngebaca torrent dari file torrent dan memasukkannya ke attribut torrent
    {
        //kamus lokal
        //File read = new File(nama);
        Scanner in;
        int i;
        ArrayList<String> strings = new ArrayList<String>();
        strings.clear(); //bersihkan dulu array masukannya
        //algoritma
        try {
            in = new Scanner(new File(NamaFileTorrent));
            while (in.hasNext()) {
                strings.add(in.nextLine());
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Torrent.class.getName()).log(Level.SEVERE, null, ex);
        }

        //System.out.println(aaa.size());
        String Baris1 = strings.get(0);
        String Baris2 = strings.get(1);
        pieces = new String[strings.size() - 2];
        for (i = 2; i < strings.size(); i++) {
            pieces[i - 2] = strings.get(i);
        }

        announce = Baris2;
        String TempArrayString[] = Baris1.split(" "); //asumsi ada 3 array maks dan pasti benar :D
        fileName = TempArrayString[0];
        infoHash = Digest.SHA1InByte(fileName);
        fileLength = Integer.parseInt(TempArrayString[1]);
        pieceSize = Integer.parseInt(TempArrayString[2]);
    }

    public byte[] BacaFile(String NamaFile) //ini baca file buat create torrent
    {
        //kamus lokal
        File file = new File(NamaFile);
        byte fileContent[] = null;
        //algoritma
        try {
            FileInputStream fin = new FileInputStream(file);
            fileContent = new byte[(int) file.length()];
            fin.read(fileContent);
            //String strFileContent = new String (fileContent)
        } catch (FileNotFoundException e) {
            System.out.println("File not found " + e);
            //return fileContent;
        } catch (IOException ioe) {
            System.out.println("Exception " + ioe);
            //return fileContent;
        }
        return fileContent;
    }

    public int getNumberPiece() {
        return (int)Math.ceil((double)fileLength / (double)pieceSize);
    }
}
